<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Laravel\Sanctum\HasApiTokens;

class UserModel extends Authenticatable
{
  /** @use HasFactory<\Database\Factories\UserFactory> */
  use HasFactory, HasApiTokens;

  public $table = 'user';
  protected $primaryKey = 'userId';

  /**
   * 获取 sanctum token
   * @return string
   */
  public function getAuthToken(): string
  {
    // 匹配 user-agent
    $pattern = '/^(\S*)\s(\([\w\s\.\;]*\))\s([\w\/\.]*)\s(\([\w\s\,]*\))\s([\w\/\.]*)\s([\w\/\.]*)/i';
    preg_match($pattern, request()->header("user-agent"), $matchArr);
    if (empty($matchArr)) {
      $android = explode(';', request()->header("user-agent"));
      if (isset($android[1])) {
        $tokenName = $android[1];
      } else {
        $tokenName = $android[0];
      }
    } else {
      $tokenName = str_replace(';', "", $matchArr[2]) . " " . $matchArr[5];
    }

    //创建token
    $expireDate = new \DateTime();
    $expireDate->setTimestamp(strtotime("+1 days"));
    $token = $this->createToken($tokenName, ['*'], $expireDate);

    return $token->plainTextToken;
  }

  /**
   * 删除当前用户 sanctum token
   * @return mixed
   */
  public function destroyAuthTokens()
  {
    return $this->tokens()->delete();
  }
}
